"""
Firebase Cloud Messaging 推送服务
用于向App发送买卖点通知
"""
import logging
import os
from typing import Optional

logger = logging.getLogger(__name__)

# Firebase Admin SDK
try:
    import firebase_admin
    from firebase_admin import credentials, messaging
    
    # 初始化 Firebase Admin SDK
    # 注意：需要将 serviceAccountKey.json 放在 backend 目录
    SERVICE_ACCOUNT_KEY_PATH = os.path.join(
        os.path.dirname(__file__), 
        'serviceAccountKey.json'
    )
    
    if os.path.exists(SERVICE_ACCOUNT_KEY_PATH):
        cred = credentials.Certificate(SERVICE_ACCOUNT_KEY_PATH)
        firebase_admin.initialize_app(cred)
        logger.info("✅ Firebase Admin SDK 初始化成功")
        FCM_ENABLED = True
    else:
        logger.warning(f"⚠️ 未找到 Firebase 配置文件: {SERVICE_ACCOUNT_KEY_PATH}")
        logger.warning("⚠️ FCM 推送功能将被禁用（测试模式）")
        FCM_ENABLED = False
        
except ImportError:
    logger.warning("⚠️ firebase-admin 未安装，FCM 推送功能将被禁用")
    logger.warning("   安装命令: pip install firebase-admin")
    FCM_ENABLED = False
except Exception as e:
    logger.error(f"❌ Firebase Admin SDK 初始化失败: {e}")
    FCM_ENABLED = False


async def send_buy_signal(
    device_token: str,
    stock_symbol: str,
    stock_name: str,
    price: float,
    reason: str
) -> bool:
    """
    发送买入信号推送
    
    Args:
        device_token: 设备FCM Token
        stock_symbol: 股票代码
        stock_name: 股票名称
        price: 当前价格
        reason: 推荐原因
    
    Returns:
        是否推送成功
    """
    try:
        if not FCM_ENABLED:
            # 测试模式：只打印日志
            logger.info(f"🧪 [测试模式] 买入信号: {stock_name}({stock_symbol}) ¥{price}")
            logger.info(f"   原因: {reason}")
            return True
        
        # 构建推送消息
        message = messaging.Message(
            data={
                'type': 'buy_signal',
                'stock_symbol': stock_symbol,
                'stock_name': stock_name,
                'signal_type': 'BUY',
                'price': str(price),
                'reason': reason
            },
            notification=messaging.Notification(
                title=f'💰 买入机会：{stock_name} ({stock_symbol})',
                body=f'价格：¥{price}\n{reason[:50]}...' if len(reason) > 50 else f'价格：¥{price}\n{reason}'
            ),
            android=messaging.AndroidConfig(
                priority='high',
                notification=messaging.AndroidNotification(
                    sound='default',
                    color='#2E7D32'  # 绿色
                )
            ),
            token=device_token
        )
        
        # 发送推送
        response = messaging.send(message)
        logger.info(f"✅ 买入信号推送成功: {stock_symbol}, 响应: {response}")
        return True
        
    except Exception as e:
        logger.error(f"❌ 买入信号推送失败: {e}")
        return False


async def send_sell_signal(
    device_token: str,
    stock_symbol: str,
    stock_name: str,
    price: float,
    reason: str
) -> bool:
    """
    发送卖出信号推送
    
    Args:
        device_token: 设备FCM Token
        stock_symbol: 股票代码
        stock_name: 股票名称
        price: 当前价格
        reason: 推荐原因
    
    Returns:
        是否推送成功
    """
    try:
        if not FCM_ENABLED:
            # 测试模式：只打印日志
            logger.info(f"🧪 [测试模式] 卖出信号: {stock_name}({stock_symbol}) ¥{price}")
            logger.info(f"   原因: {reason}")
            return True
        
        # 构建推送消息
        message = messaging.Message(
            data={
                'type': 'sell_signal',
                'stock_symbol': stock_symbol,
                'stock_name': stock_name,
                'signal_type': 'SELL',
                'price': str(price),
                'reason': reason
            },
            notification=messaging.Notification(
                title=f'📉 卖出提醒：{stock_name} ({stock_symbol})',
                body=f'价格：¥{price}\n{reason[:50]}...' if len(reason) > 50 else f'价格：¥{price}\n{reason}'
            ),
            android=messaging.AndroidConfig(
                priority='high',
                notification=messaging.AndroidNotification(
                    sound='default',
                    color='#C62828'  # 红色
                )
            ),
            token=device_token
        )
        
        # 发送推送
        response = messaging.send(message)
        logger.info(f"✅ 卖出信号推送成功: {stock_symbol}, 响应: {response}")
        return True
        
    except Exception as e:
        logger.error(f"❌ 卖出信号推送失败: {e}")
        return False


async def send_batch_update(
    device_token: str,
    buy_count: int,
    sell_count: int
) -> bool:
    """
    发送批量更新通知
    
    Args:
        device_token: 设备FCM Token
        buy_count: 买入信号数量
        sell_count: 卖出信号数量
    
    Returns:
        是否推送成功
    """
    try:
        if not FCM_ENABLED:
            # 测试模式：只打印日志
            logger.info(f"🧪 [测试模式] 批量更新: {buy_count}个买入, {sell_count}个卖出")
            return True
        
        # 构建推送消息
        message = messaging.Message(
            data={
                'type': 'batch_update',
                'buy_count': str(buy_count),
                'sell_count': str(sell_count)
            },
            notification=messaging.Notification(
                title='📊 股票监控更新',
                body=f'发现 {buy_count} 个买入机会，{sell_count} 个卖出提醒'
            ),
            android=messaging.AndroidConfig(
                priority='default',
                notification=messaging.AndroidNotification(
                    sound='default'
                )
            ),
            token=device_token
        )
        
        # 发送推送
        response = messaging.send(message)
        logger.info(f"✅ 批量更新推送成功, 响应: {response}")
        return True
        
    except Exception as e:
        logger.error(f"❌ 批量更新推送失败: {e}")
        return False


async def send_test_notification(device_token: str) -> bool:
    """
    发送测试通知（用于验证推送功能）
    
    Args:
        device_token: 设备FCM Token
    
    Returns:
        是否推送成功
    """
    try:
        if not FCM_ENABLED:
            logger.info(f"🧪 [测试模式] 测试通知发送到: {device_token[:20]}...")
            return True
        
        message = messaging.Message(
            notification=messaging.Notification(
                title='🎉 推送测试',
                body='恭喜！推送服务配置成功，您可以正常接收买卖点通知了。'
            ),
            android=messaging.AndroidConfig(
                priority='high',
                notification=messaging.AndroidNotification(
                    sound='default'
                )
            ),
            token=device_token
        )
        
        response = messaging.send(message)
        logger.info(f"✅ 测试通知推送成功, 响应: {response}")
        return True
        
    except Exception as e:
        logger.error(f"❌ 测试通知推送失败: {e}")
        return False


def is_fcm_enabled() -> bool:
    """检查FCM是否已启用"""
    return FCM_ENABLED

